/**
 * @file bsp_lora.c
 * @brief lora驱动
 * @author wangh (wanghuan3037@fiberhome.com)
 * @version 1.0
 * @date 2020-04-10
 * @copyright Copyright (c) 2020  烽火通信
 ***************************************************************
 * @par 修改日志:
 */
#include <string.h>
#include "bsp_lora.h"
#include "sx1276.h"
#include "sx1276-LoRa.h"
#include "sx1276-LoRaMisc.h"
#include "FreeRTOS.h"
#include "task.h"

tRadioDriver *Radio = NULL;

/**
 * @brief lora初始化 \n
 * 也可通过修改默认 LoRaSettings 中的参数来初始化
 * 使用自定义初始化之前调用SX1276Init()
 */
void lora_init(uint32_t freq)
{
	Radio = RadioDriverInit();
	Radio->Init();
    SX1276LoRaSetRFFrequency( freq );
	
#if 0
	SX1276Init();
	
	SX1276LoRaSetRFState(RFLR_STATE_IDLE);
	
    // set the RF settings  
	SX1276LoRaSetRFFrequency( LORA_RFFrequency );
    SX1276LoRaSetSpreadingFactor( 7 ); // SF6 only operates in implicit header mode.
    SX1276LoRaSetErrorCoding( 2 );
    SX1276LoRaSetPacketCrcOn( true );
    SX1276LoRaSetSignalBandwidth( 9 );

    SX1276LoRaSetImplicitHeaderOn( false );
    SX1276LoRaSetSymbTimeout( 0x3FF );
    SX1276LoRaSetPayloadLength( 128 );
    SX1276LoRaSetLowDatarateOptimize( true );
	
	// set the PA
	SX1276LoRaSetPAOutput( RFLR_PACONFIG_PASELECT_PABOOST );
	SX1276LoRaSetPa20dBm( true );
	SX1276LoRaSetPaRamp( 9 );	//FSK 模式下斜升/斜降时间 40us
	SX1276LoRaSetRFPower( 20 );
	  
//	SX1276LoRaSetRxSingleOn(false);
//	SX1276LoRaSetFreqHopOn(false);
//	SX1276LoRaSetHopPeriod(10);
		
    SX1276LoRaSetOpMode( RFLR_OPMODE_STANDBY );
#endif
}

/**
 * @brief lora发送
 * @param  buff         发送缓存
 * @param  size         发送长度
 * @param  freq         发送频率
 * @return uint8_t 
 */
uint8_t lora_send(uint8_t *buff, uint16_t size, uint32_t freq, uint16_t timeout)
{
	SX1276LoRaSetRFFrequency( freq );
	SX1276SetTxPacket(buff, size);
    
	uint32_t TxTimeoutTimer = xTaskGetTickCount();
    while( SX1276Process( ) != RF_TX_DONE )
    {
        if( ( xTaskGetTickCount() - TxTimeoutTimer ) > timeout )
            return 1;
    }
      
    return 0;
}

/**
 * @brief lora接收
 * @param  buff         接收缓存
 * @param  size         接收长度
 * @param  freq         接收频率 (Hz)
 * @param  timeout      接收超时时间 (ms)
* @return uint8_t      0:成功， 1：超时
 */
uint8_t lora_recv(uint8_t *buff, uint16_t *size, uint32_t freq, bool RxSingleOn, uint16_t timeout)
{
	uint32_t ret;
	
	SX1276LoRaSetRFFrequency( freq );
	SX1276LoRaSetRxPacketTimeout( timeout );
	SX1276LoRaSetRxSingleOn(RxSingleOn);
    SX1276StartRx(); 
  
    while(1)  
    {
        ret = SX1276Process( );  
        if( (ret == RF_RX_DONE) || (ret == RF_RX_TIMEOUT) )  
        {  
            break;  
        }  
    }  
      
    if( ret == RF_RX_DONE )  
    {  
		SX1276GetRxPacket( buff, size );   
    }  
    else  
    {  
        return 1;  
    }
	
	return 0;
}


/*********** (C) COPYRIGHT 2020 FiberHome *****END OF FILE****/
